package client

import (
	"awesomeTask/application/variable"
	"awesomeTask/commom/MessageHelper"
	awesomeTask "awesomeTask/config"
	"awesomeTask/system/event"
	"awesomeTask/system/kernel"
	"fmt"
	"net"
	"strconv"
)

type EventClientHandlerObj struct {
}

/**
子节点会定期报告剩余系统资源,cpu负载,内存剩余数,当前运行的任务数量,这里做一个存储
*/
func (handler EventClientHandlerObj) PostNodeStatus() {
	status := kernel.GetKernelDriver().GetNodeCpuUseAndMemory()
	status["bindIp"] = awesomeTask.GetConfigByKey("listenIpAddress")
	status["bindPort"] = awesomeTask.GetConfigByKey("listenPort")
	status["location"] = awesomeTask.GetConfigByKey("location")
	variable.ServerConnections.Range(func(key, value interface{}) bool {
		MessageHelper.SendEvent("RecordNodeInfo", status, value.(net.Conn))
		return true
	})
}

//通知某个节点当前的数据情况
func (handler EventClientHandlerObj) PostNodeStatusOne(con net.Conn) {
	status := kernel.GetKernelDriver().GetNodeCpuUseAndMemory()
	status["bindIp"] = awesomeTask.GetConfigByKey("listenIpAddress")
	status["bindPort"] = awesomeTask.GetConfigByKey("listenPort")
	status["location"] = awesomeTask.GetConfigByKey("location")
	MessageHelper.SendEvent("RecordNodeInfo", status, con)
}

/**
此处执行具体的任务逻辑
*/
func (handler EventClientHandlerObj) RunTask(info map[string]interface{}) {
	data := info["taskInfo"].(map[string]interface{})
	fmt.Println("开始执行任务")
	variable.CurrentRunningTaskNum += 1
	handler.PostNodeStatus()
	taskId := data["task_id"].(float64)
	driver := kernel.GetKernelDriver().(kernel.Kernel)
	runningMessage := driver.ExceShellOrBash(awesomeTask.GetConfigByKey("taskCommand").(string)+" "+strconv.Itoa(int(taskId)), false)
	variable.CurrentRunningTaskNum -= 1
	fmt.Println("任务执行完成")
	message := runningMessage
	data1 := make(map[string]interface{})
	data1["taskId"] = taskId
	data1["runningInfo"] = message
	MessageHelper.SendEvent(variable.GetEventMap(variable.ON_ClIENT_TASK_FINISH), data1, GetServerCon())
	event.Dispatch(variable.ON_ClIENT_TASK_FINISH, data["task_id"], runningMessage)
	handler.PostNodeStatus()
}

func (handler EventClientHandlerObj) RegisterConfig() {
	serverConfig := make(map[string]interface{})
	registerKeys := []string{
		"toMaster",
		"listenPort",
		"listenIpAddress",
	}
	for _, key := range registerKeys {
		serverConfig[key] = awesomeTask.GetConfigByKey(key)
	}
	MessageHelper.SendEvent(variable.ON_REGISTER_SERVER, serverConfig, GetServerCon())
}

func SendEventToAll(event string, eventInfo map[string]interface{}) {
	variable.ServerConnections.Range(func(key, value interface{}) bool {
		go MessageHelper.SendEvent(event, eventInfo, value.(net.Conn))
		return true
	})
}
